package cn.school.ajax;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.school.entity.Grade;
import cn.school.entity.Student;
import cn.school.servies.GradeSerive;
import cn.school.servies.StudentSerive;
import cn.school.tool.StringKit;

/**
 * Servlet implementation class StudentUpdateAjax
 */
@WebServlet("/StudentUpdateAjax")
public class StudentUpdateAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public StudentUpdateAjax() {
		super();
		// TODO Auto-generated constructor stub
	}

	StudentSerive ss = new StudentSerive();
	GradeSerive gs = new GradeSerive();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("application/json; charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		long stuno = StringKit.toLong(request.getParameter("stuno"));
		Student student = ss.serch1(stuno);
		// String stu=JSON.toJSONString(student);
		List<Grade> list = gs.findAll();
		// String mes="{\"student\":"+student+",\"list\":"+list+"}";
		String stu = JSON.toJSONStringWithDateFormat(student, "yyyy-MM-dd", SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteMapNullValue);
		String list1 = JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd", SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteMapNullValue);
		String mes = "{\"stu\":" + stu + ",\"list1\":" + list1 + "}";
		// System.out.println(mes);
		response.getWriter().print(mes);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// doGet(request, response);
		response.setContentType("application/json; charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		System.out.println("进入post");
		// 获取application 对象
		ServletContext application = super.getServletContext();

		// ServletContext application=this.getServletContext();

		// 获得工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 100);

		// 读取文件
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");

		// 迭代文件
		List<FileItem> list = null;
		try {
			list = (List<FileItem>) upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Student stu = new Student();

		for (FileItem f : list) {
			System.out.println("进入迭代");
			if (f.isFormField()) {
				// 表单元素
				System.out.println("名称：" + f.getFieldName() + ",值：" + f.getString("utf-8"));
				if (f.getFieldName().equals("stuno")) {
					stu.setStuno(StringKit.toLong(f.getString("utf-8")));
				}
				if (f.getFieldName().equals("sname")) {
					stu.setSname(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("sex")) {

					stu.setSex(f.getString("utf-8"));

				}
				if (f.getFieldName().equals("telephone")) {
					stu.setTelephone(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("qq")) {
					stu.setQq(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("wechat")) {
					stu.setWechat(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("gradeid")) {
					stu.setGradeid(Long.parseLong(f.getString("utf-8")));
				}
				if (f.getFieldName().equals("enterdate")) {
					stu.setEnterdate(StringKit.toDate(f.getString("utf-8")));
				}
				if (f.getFieldName().equals("fromcity")) {
					stu.setFromcity(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("birthday")) {
					stu.setBirthday(StringKit.toDate(f.getString("utf-8")));
				}
				if (f.getFieldName().equals("address")) {
					stu.setAddress(f.getString("utf-8"));
				}
				if (f.getFieldName().equals("pass")) {
					stu.setPass(f.getString("utf-8"));
				}

			} else {
				// 文件元素
				if (f.getSize() == 0) {
					continue;
				}
				File path = new File(application.getRealPath("imges"));

				if (path.exists() == false) {
					path.mkdir();
				}

				String tupian = f.getName().substring(f.getName().lastIndexOf("."));
				String newName = UUID.randomUUID() + tupian;
				try {
					f.write(new File(path, newName));
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				stu.setPhoto("imges/" + newName);
			}

		}
		int a = ss.update(stu);
		System.out.println("结果：" + a);
		String g = null;
		if (a > 0) {
			g = "{\"gx\":true}";
			// gx="更新成功";

		} else {
			g = "{\"gx\":false}";
			// gx="更新失败";

		}
		System.out.println("gx:" + g);
		response.getWriter().print(g);
	}

}
